package com.dzsw.javabase.number;

import java.util.ArrayList;
import java.util.List;

public class Number2CharSample {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 52; i++) {
            String columnHeader = excelColNum2Str(i);
            list.add(columnHeader);
            System.out.println("COL["+ i + "]=" + columnHeader + "," + number2Char(i));
        }
        for (int i = 0; i < list.size(); i++) {
            System.out.println("COL["+ list.get(i) + "]=" + excelColStr2Num(list.get(i)));
        }
    }

    public static String number2Char(int num) {
        String str = "";

        int num1;
        int num2;

        if (num == 0) {
            return str;
        }

        num1 = num / 26;
        num2 = num % 26;

        str = number2Char(num1) + String.valueOf((char) ('A' + num2));

        return str;
    }

    /**
     * excel 列字符串转列数，列数从 0 开始。
     *
     * @param str column header string
     * @return number of column
     */
    public static int excelColStr2Num(String str) {
        int num, result = 0;
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(len - i - 1); // 从最后往前
            num = ch - 'A' + 1;
            num *= Math.pow(26, i);
            result += num;
        }
        return result - 1;
    }

    /**
     * excel 列数转列字符串，列数从 0 开始。
     *
     * @param num column of number
     * @return number of column
     */
    public static String excelColNum2Str(int num) {
        if (num < 0) {
            return null;
        }
        num += 1;
        String str = "";
        int quotient, remainder; // 商，余数
        do {
            quotient = (num - 1) / 26;
            remainder = (num - 1) % 26;
            str = (char) (remainder + 'A') + str;
            num = quotient;
        } while (num > 0);
        return str;
    }
}
